package com.shushan.ui;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextWatcher;
import android.text.method.PasswordTransformationMethod;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.shushan.shushanbao.R;


/**
 * @ClassName: VeriCodeNoView
 * @Desciption: 自定义验证码输入框view(默认不显示软键盘)
 * @author: yichaohua
 * @date: 2018-09-20
 */
public class VeriCodeNoView extends LinearLayout implements TextWatcher{

    private static final String TAG = "VeriCodeNoView";

    private Context mContext;
    private long endTime = 0;
    private VerificationCodeView.OnCodeFinishListener onCodeFinishListener;

    /**
     * 输入框数量
     */
    private int mEtNumber;

    /**
     * 输入框的宽度
     */
    private int mEtWidth;

    /**
     * 输入框的高度
     */
    private int mEtHeight;

    /**
     * 文字颜色
     */
    private int mEtTextColor;

    /**
     * 文字大小
     */
    private float mEtTextSize;

    /**
     * 输入框背景
     */
    private int mEtTextBg;

    public VerificationCodeView.OnCodeFinishListener getOnCodeFinishListener() {
        return onCodeFinishListener;
    }

    public void setOnCodeFinishListener(VerificationCodeView.OnCodeFinishListener onCodeFinishListener) {
        this.onCodeFinishListener = onCodeFinishListener;
    }

    public int getmEtNumber() {
        return mEtNumber;
    }

    public void setmEtNumber(int mEtNumber) {
        this.mEtNumber = mEtNumber;
    }

    public int getmEtWidth() {
        return mEtWidth;
    }

    public void setmEtWidth(int mEtWidth) {
        this.mEtWidth = mEtWidth;
    }

    public int getmEtHeight() {
        return mEtHeight;
    }

    public void setmEtHeight(int mEtHeight) {
        this.mEtHeight = mEtHeight;
    }

    public int getmEtTextColor() {
        return mEtTextColor;
    }

    public void setmEtTextColor(int mEtTextColor) {
        this.mEtTextColor = mEtTextColor;
    }

    public float getmEtTextSize() {
        return mEtTextSize;
    }

    public void setmEtTextSize(float mEtTextSize) {
        this.mEtTextSize = mEtTextSize;
    }

    public int getmEtTextBg() {
        return mEtTextBg;
    }

    public void setmEtTextBg(int mEtTextBg) {
        this.mEtTextBg = mEtTextBg;
    }


    public VeriCodeNoView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
        @SuppressLint({"Recycle", "CustomViewStyleable"})
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.vericationCodeView);
        mEtNumber = typedArray.getInteger(R.styleable.vericationCodeView_vcv_et_number, 4);
        mEtWidth = typedArray.getDimensionPixelSize(R.styleable.vericationCodeView_vcv_et_width, 120);
        mEtHeight = typedArray.getDimensionPixelSize(R.styleable.vericationCodeView_vcv_et_height, 120);
        mEtTextColor = typedArray.getColor(R.styleable.vericationCodeView_vcv_et_text_color, Color.BLACK);
        mEtTextSize = typedArray.getDimensionPixelSize(R.styleable.vericationCodeView_vcv_et_text_size, 16);
        mEtTextBg = typedArray.getResourceId(R.styleable.vericationCodeView_vcv_et_bg, R.drawable.bg_et_input_veri_code);

        //释放资源
        typedArray.recycle();
        initView();
    }

    @SuppressLint("ResourceAsColor")
    private void initView() {
        for (int i = 0; i < mEtNumber; i++) {
            EditText editText = new EditText(mContext);
            editText.setEnabled(false);
            editText.setFocusable(false);
            editText.setFocusableInTouchMode(false);
            initEditText(editText, i);
            addView(editText);
        }
    }

    private void initEditText(EditText editText, int i) {
        int childHPadding = 0;
        int childVPadding = 0;

        LayoutParams layoutParams = new LayoutParams(mEtWidth,mEtHeight);
        layoutParams.bottomMargin = childVPadding;
        layoutParams.topMargin = childVPadding;
        layoutParams.leftMargin = childHPadding;
        layoutParams.rightMargin = childHPadding;
        layoutParams.gravity = Gravity.CENTER;
        editText.setLayoutParams(layoutParams);
        editText.setGravity(Gravity.CENTER);
        editText.setId(i);
        editText.setCursorVisible(true);
        editText.setMaxEms(1);
        editText.setTextColor(mEtTextColor);
        editText.setTextSize(mEtTextSize);
        editText.setMaxLines(1);
        editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(1)});
        editText.setInputType(InputType.TYPE_NUMBER_VARIATION_PASSWORD);
        editText.setTransformationMethod(PasswordTransformationMethod.getInstance());
        editText.setPadding(0, 0, 0, 0);
        if(mEtTextBg != 0) {
            editText.setBackgroundResource(mEtTextBg);
        }

        editText.addTextChangedListener(this);
    }


    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        if (s.length() != 0) {
            //如果最后一个输入框有字符，则返回结果
            EditText lastEditText = (EditText) getChildAt(mEtNumber - 1);
            if (lastEditText.getText().length() > 0) {
                getResult();
            }
        }
    }

    @Override
    public void setEnabled(boolean enabled) {
        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            View child = getChildAt(i);
            child.setEnabled(enabled);
        }
    }

    public void setText(int text) {
        long startTime = System.currentTimeMillis();
        EditText editText;
        if(text >= 0){
            for (int i = 0; i < mEtNumber; i++) {
                editText = (EditText) getChildAt(i);
                if(editText != null && editText.getText().length() <= 0 && startTime - endTime > 100){
                    editText.setText(text+"");
                    endTime = startTime;
                    break;
                }
            }
        }else {
            for (int i = mEtNumber-1; i >= 0; i--) {
                editText = (EditText) getChildAt(i);
                if(editText != null && editText.getText().length() > 0 && startTime - endTime > 100){
                    editText.setText("");
                    endTime = startTime;
                    break;
                }
            }
        }

    }

    private void getResult() {
        StringBuffer stringBuffer = new StringBuffer();
        EditText editText;
        for (int i = 0; i < mEtNumber; i++) {
            editText = (EditText) getChildAt(i);
            stringBuffer.append(editText.getText());
        }
        if (onCodeFinishListener != null) {
            onCodeFinishListener.onComplete(stringBuffer.toString());
        }
    }

    public void clear(){
        for (int i = 0; i < mEtNumber; i++) {
            EditText editText = (EditText) getChildAt(i);
            editText.setText("");
        }

    }

    public interface OnCodeFinishListener {
        void onComplete(String content);
    }
}
